# -*- coding: utf-8 -*-
# ㊎ Author : XMZ
# ㊍ Time : 2021/5/2 12:49
# ㊌ File : RabbitMQ -> consumer
# ㊋ IDE :PyCharm
# ㊏ 
import os
import sys
import time

import pika

self_path = os.path.dirname(os.path.abspath(__file__))
father_path = os.path.dirname(self_path)
parent_path = os.path.dirname(father_path)
sys.path.append(self_path)
sys.path.append(father_path)
sys.path.append(parent_path)

my_host = "10.0.2.22"
name = "admin"
pwd = "123456"
# 创建登录对象
credentials = pika.PlainCredentials(username=name, password=pwd)
# 创建RabbitMQ的链接对象
connections = pika.BlockingConnection(
    pika.ConnectionParameters(
        host=my_host,
        credentials=credentials,
        heartbeat=0,
    ))
# 创建链接RabbitMQ 的管道对象
channel = connections.channel()
# 创建 exchange 交换机
channel.exchange_declare(exchange="log", exchange_type="direct")
# 创建匿名队列 exclusive=True 表示没有与当前队列连接，队列自动删除
result = channel.queue_declare(queue="", exclusive=True)
queue_name = result.method.queue
print(f'自动创建的队列名：{result}')
# 绑定队列到交换机 exchange
channel.queue_bind(exchange="log", queue=queue_name, routing_key="warning")


# 定义消息队列处理 函数
def callback(ch, method, properties, body):
    time.sleep(1)
    print(f"打印出的消息:  {body.decode()}")
    # 消息处理之后，确认消息
    ch.basic_ack(delivery_tag=method.delivery_tag)


# 设置公平调度
channel.basic_qos(prefetch_count=1)

# 关联队列、并设置队列中消息的处理函数
channel.basic_consume(
    queue=queue_name,  # 队列名称；
    on_message_callback=callback,  # 消费函数；
    auto_ack=False,  # 是否自动确认
    exclusive=False,  # 为False时 该队列可以被其他消费者连接 反之不可以
)

# 启动并开始处理消息
channel.start_consuming()
